object RecursiveFunctionDemo extends App {
  def factorial(n: Int): Int = {
    if (n <= 1) 1
    else n * factorial(n - 1)
  }

  def sortScores(scores: List[Int]): List[Int] = {
    if (scores.length <= 1) scores
    else {
      val pivot = scores.head
      val (lessOrEqual, greater) = scores.tail.partition(_ <= pivot)
      sortScores(lessOrEqual) ::: List(pivot) ::: sortScores(greater)
    }
  }

  def calculateRanks(scores: List[Int], sortedScores: List[Int] = Nil): List[Int] = {
    if (scores.isEmpty) Nil
    else {
      val currentScore = scores.head
      val sorted = if (sortedScores.isEmpty) sortScores(scores).reverse else sortedScores
      val rank = sorted.indexOf(currentScore) + 1
      rank :: calculateRanks(scores.tail, sorted)
    }
  }

  println("阶乘计算：")
  println(s"5的阶乘是：${factorial(5)}")

  val mathScores = List(85, 92, 76, 88, 90, 76, 85, 92)
  println(s"\n原始成绩：$mathScores")

  val sorted = sortScores(mathScores)
  println(s"排序后（升序）：$sorted")

  val ranks = calculateRanks(mathScores)
  println(s"对应名次：$ranks")

  case class Student(name: String, score: Int)
  val students = List(
    Student("张三", 85),
    Student("李四", 92),
    Student("王五", 76),
    Student("赵六", 88)
  )

  def findTopStudents(students: List[Student]): List[Student] = {
    if (students.isEmpty) Nil
    else {
      val topScore = students.map(_.score).max
      students.filter(_.score == topScore)
    }
  }

  val topStudents = findTopStudents(students)
  println(s"\n最高分学生：${topStudents.map(_.name).mkString(", ")}，分数：${topStudents.head.score}")
}
//第十周（11.03【动手练习 4】：实现课程成绩排名功能